#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/6/17 21:37
# @FileName: studio-upload.py
# @Software: PyCharm
import os
import sys
import click
import base64
import logging
from pathlib import Path
import tempfile
import requests
import zipfile
from urllib.parse import unquote

from repo_uploaders.repo_manager import RepoManagerFactory
from repo_uploaders.impls.obs_apt_repo_manager import OBSPipeLineLogHelper

OBS_AK = os.getenv("ak")
OBS_SK = os.getenv("sk")
OBS_ENDPOINT = os.getenv("obs_endpoint")
PUBLIC_KEY = os.getenv("public_key")
PRIVATE_KEY = os.getenv("private_key")
APT_BUCKET = os.getenv("apt_bucket_name")
OBS_ROOT = os.getenv("obs_root")
GPG_PASSPHRASE = os.getenv("passphrase")
DEBUG_INFO = os.getenv("DEBUG") == "True"
STUDIO_ZIP_URL = "https://repo.openubmc.cn/latest/tools/BMC%20Studio.zip"

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")


def download_and_extract_deb(url):
    logging.info(f"尝试从 {url} 获取bmc-studio的deb文件...")
    try:
        # 创建临时目录
        temp_dir = tempfile.mkdtemp()
        logging.info(f"创建临时目录: {temp_dir}")

        # 下载文件
        logging.info(f"正在下载: {url}")
        response = requests.get(url, stream=True)
        response.raise_for_status()

        # 处理URL编码的文件名
        filename = unquote(url.split('/')[-1])
        zip_path = os.path.join(temp_dir, filename)

        # 保存ZIP文件
        with open(zip_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        logging.info(f"文件已保存到: {zip_path}")

        # 解压ZIP文件
        logging.info("正在解压文件...")
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(temp_dir)
        logging.info(f"文件已解压到: {temp_dir}")

        # 查找.deb文件
        deb_files = list(Path(temp_dir).rglob('*.deb'))
        if not deb_files:
            raise FileNotFoundError("解压目录中未找到.deb文件")

        # 返回第一个.deb文件的绝对路径
        deb_path = str(deb_files[0].absolute())
        logging.info(f"找到.deb文件: {deb_path}")
        return deb_path

    except Exception as e:
        logging.info(f"处理过程中发生错误: {str(e)}")
        raise


@click.command()
@click.option("--codename")
@click.option("--component")
@click.option("--arch")
def main(codename, component, arch):
    params = [OBS_AK, OBS_SK, OBS_ENDPOINT, APT_BUCKET, codename, component, arch, PUBLIC_KEY, PRIVATE_KEY]

    if DEBUG_INFO:
        logging.info(">>>>")
        logging.info(params)
        logging.info("<<<<")

    if not all(params):
        logging.info(f"Lack of params{params}, Please check.")
        sys.exit(-1)
    
    deb_path = download_and_extract_deb(STUDIO_ZIP_URL)
    deb_full_path = Path(deb_path)
    logging.info("deb: {}".format(deb_full_path))

    apt_mgr = RepoManagerFactory.create(
        "obs", deb_full_path, codename, component, arch, OBS_ROOT, is_debug=DEBUG_INFO)

    decoded_private_key = base64.b64decode(PRIVATE_KEY).decode()
    
    apt_mgr.init_apt_helper(OBS_AK, OBS_SK, OBS_ENDPOINT, APT_BUCKET)
    apt_pkg = apt_mgr.prepare_package(decoded_private_key, GPG_PASSPHRASE)
    apt_mgr.upload_package(apt_pkg, PUBLIC_KEY)


if __name__ == '__main__':
    main()
